//
//  LZAlertView.m
//  laziz_Consumer
//
//  Created by xbn_iMac on 2016/11/15.
//  Copyright © 2016年 XBN. All rights reserved.
//

#import "LZAlertView.h"
#import "LZAlertBaseCustomView.h"
#import "LZAlertNormalImageCustomView.h"
#import "LZAlertNormalTextCustomView.h"
#import "Masonry.h"

@interface LZAlertViewManager ()

@end

@implementation LZAlertViewManager

+ (instancetype)shareInstance {
    static LZAlertViewManager *lzAlertViewManager;
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        lzAlertViewManager = [[LZAlertViewManager alloc] init];
    });
    
    return lzAlertViewManager;
}

@end

@interface LZAlertView ()

@property (nonatomic, strong) UIView *viewAlert;    // alert的主View
@property (nonatomic, strong) LZAlertBaseCustomView *topView;

@property (nonatomic, copy) NSString *strCancel;
@property (nonatomic, strong) NSMutableArray *arrOtherButtonsTitles;
@property (nonatomic, strong) NSMutableArray *arrButtons;
@property (nonatomic, assign) float padding;
@property (nonatomic, assign) float itemHeight;

@end

@implementation LZAlertView

-(instancetype)initWithContent:(NSString*)content andImage:(UIImage*)aImage cancelButtonTitle:(NSString*)cancel otherButtonTitles:(NSString*)otherButtonTitles, ... NS_REQUIRES_NIL_TERMINATION{
    self = [super initWithFrame:[UIApplication sharedApplication].keyWindow.bounds];
    if (self) {
        
        if (aImage) {
            LZAlertBaseCustomView *v = [LZAlertNormalImageCustomView initNormalViewWithMessage:content andImage:aImage];
            self.topView = v;
        }
        else {
            LZAlertBaseCustomView *v = [LZAlertNormalTextCustomView initNormalViewWithMessage:content];
            self.topView = v;
        }
        
        if (cancel) {
            self.strCancel = [cancel copy];
        }
        
        self.backgroundColor = [UIColor colorWithWhite:0 alpha:0.7];
        
        self.padding = 0.8;
        self.itemHeight = 50;
        self.arrOtherButtonsTitles = [NSMutableArray array];
        self.arrButtons = [NSMutableArray array];
        
        NSLog(@"%@",otherButtonTitles);
        if (otherButtonTitles) {
            [self.arrOtherButtonsTitles addObject:otherButtonTitles];
        }
        
        va_list args;
        va_start(args, otherButtonTitles);
        if (otherButtonTitles)
        {
            NSString *otherString;
            while ((otherString = va_arg(args, NSString *)))
            {
                //依次取得所有参数
                NSLog(@"%@",otherString);
                [self.arrOtherButtonsTitles addObject:otherString];
            }
        }
        va_end(args);
        
        [self initAlertView];
    }
    return self;
}

-(instancetype)initWithCustomTopView:(LZAlertBaseCustomView*)aView cancelButtonTitle:(NSString*)cancel otherButtonTitles:(NSString*)otherButtonTitles, ... {
    self = [super initWithFrame:[UIApplication sharedApplication].keyWindow.bounds];
    if (self) {
        
        self.topView = aView;
        
        if (cancel) {
            self.strCancel = [cancel copy];
        }
        
        self.backgroundColor = [UIColor colorWithWhite:0 alpha:0.6];
        
        self.padding = 0.8;
        self.itemHeight = 50;
        self.arrOtherButtonsTitles = [NSMutableArray array];
        self.arrButtons = [NSMutableArray array];
        
        NSLog(@"%@",otherButtonTitles);
        if (otherButtonTitles) {
            [self.arrOtherButtonsTitles addObject:otherButtonTitles];
        }
        
        va_list args;
        va_start(args, otherButtonTitles);
        if (otherButtonTitles)
        {
            NSString *otherString;
            while ((otherString = va_arg(args, NSString *)))
            {
                //依次取得所有参数
                NSLog(@"%@",otherString);
                [self.arrOtherButtonsTitles addObject:otherString];
            }
        }
        va_end(args);
        
        [self initAlertView];
    }
    return self;
}

#pragma mark - 部分控件和属性的get和set方法

-(void)setTopView:(LZAlertBaseCustomView *)topView {
    if (topView == nil) {
        _topView = [[LZAlertBaseCustomView alloc] initWithFrame:CGRectMake(0, 0, 0, 30)];
    }
    else {
        _topView = topView;
    }
    _topView.backgroundColor = [UIColor whiteColor];
}

-(UIColor*)buttonsColor {
    if (_buttonsColor) {
        return _buttonsColor;
    }
    return UIColorFromRGB(0xff7a21, 1);
}

-(UIColor*)cancelColor {
    if (_cancelColor) {
        return _cancelColor;
    }
    return UIColorFromRGB(0x333333, 1);
}


#pragma mark - 部分控件的get和set方法

// 初始化alert
-(void)initAlertView {
    
    [self createAlertView];
    
    [self createCustomTopView];
    
    [self createButtons];
    
    [self initVFLs];
}

// 创建alert的主View
-(void)createAlertView {
    
    _viewAlert = [[UIView alloc] init];
    self.viewAlert.layer.cornerRadius = 5.f;
    self.viewAlert.center = self.center;
    self.viewAlert.backgroundColor = [UIColor colorWithRed:238./255. green:238./255. blue:238./255. alpha:1];
    self.viewAlert.clipsToBounds = YES;
    [self addSubview:_viewAlert];
}

// 添加头部自定义view
-(void)createCustomTopView {
    
    [self.viewAlert addSubview:_topView];
    
}

// 创建按钮并添加到按钮数组中
-(void)createButtons {
    int buttonTag = 0;
    
    UIButton *cancelButton = nil;
    if (self.strCancel) {
        // 如果有取消按钮
        UIButton *btn = [self createButton:self.strCancel textColor:self.cancelColor];
        btn.tag = buttonTag;
        [self.viewAlert addSubview:btn];
        cancelButton = btn;
        buttonTag ++;
    }
    
    for (int i = 0; i<self.arrOtherButtonsTitles.count; i++) {
        UIButton *btn = [self createButton:self.arrOtherButtonsTitles[i] textColor:self.buttonsColor];
        btn.tag = buttonTag;
        [self.viewAlert addSubview:btn];
        [self.arrButtons addObject:btn];
        buttonTag ++;
    }
    
    if (cancelButton) {
        [self.arrButtons addObject:cancelButton];
    }
}

// 设置alert的主View、头部自定义view和按钮的vfl
-(void)initVFLs {
    
    // 头部自定义view
    [self.topView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(0);
        make.leading.mas_equalTo(0);
        make.trailing.mas_equalTo(0);
        make.height.mas_equalTo(CGRectGetHeight(self.topView.frame));
    }];
    
    // 按钮等宽、从右向左横向排列
    [self makeEqualWidthViews:self.arrButtons inView:self.viewAlert LRpadding:0 viewPadding:self.padding];
    
    // alert的主View
    
    [self.viewAlert mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.mas_centerX);
        make.centerY.equalTo(self.mas_centerY);
        make.width.mas_equalTo(self.topView.customWidth);
        make.height.mas_equalTo(self.itemHeight+CGRectGetHeight(self.topView.frame));
    }];
}

/**
 *  将若干view等宽布局于容器containerView中
 *
 *  @param views         viewArray
 *  @param containerView 容器view
 *  @param LRpadding     距容器的左右边距
 *  @param viewPadding   各view的左右边距
 */
-(void)makeEqualWidthViews:(NSArray *)views inView:(UIView *)containerView LRpadding:(CGFloat)LRpadding viewPadding :(CGFloat)viewPadding
{
    UIView *lastView;
    for (UIButton *view in views) {
        
        if (lastView) {
            [view mas_makeConstraints:^(MASConstraintMaker *make) {
                make.top.equalTo(self.topView.mas_bottom).offset(viewPadding);
                make.trailing.equalTo(lastView.mas_leading).offset(-viewPadding);
                make.width.equalTo(lastView.mas_width);
                make.height.mas_equalTo(self.itemHeight);
            }];
        }else
        {
            [view mas_makeConstraints:^(MASConstraintMaker *make) {
                make.trailing.equalTo(containerView).offset(LRpadding);
                make.top.equalTo(self.topView.mas_bottom).offset(viewPadding);
                make.height.mas_equalTo(self.itemHeight);
            }];
        }
        lastView=view;
    }
    [lastView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.equalTo(containerView).offset(LRpadding);
    }];
}

// 创建按钮并设置title和字体color
-(UIButton*)createButton:(NSString*)title textColor:(UIColor*)color {
    UIButton *button = [[UIButton alloc] init];
    button.backgroundColor = [UIColor whiteColor];
    [button setTitle:title forState:UIControlStateNormal];
    [button setTitleColor:color forState:UIControlStateNormal];
    button.titleLabel.font = [UIFont systemFontOfSize:14];
    [button addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
    [button addTarget:self action:@selector(buttonBackGroundHighlighted:) forControlEvents:UIControlEventTouchDown];
    
    [button addTarget:self action:@selector(buttonBackGroundUpOutside:) forControlEvents:UIControlEventTouchUpOutside];
    
    return button;
}

// button点击事件/普通状态下的背景色
-(void)buttonAction:(UIButton*)sender {
    NSLog(@"点击了第%ld个按钮",(long)sender.tag);
    sender.backgroundColor = [UIColor whiteColor];
    if (self.clickButtonIndexBlock) {
        self.clickButtonIndexBlock(sender.tag);
    }
    [self close];
}

//  button高亮状态下的背景色
- (void)buttonBackGroundHighlighted:(UIButton *)sender
{
    sender.backgroundColor = [UIColor colorWithWhite:0.85 alpha:1];
}

//  button点击取消状态下的背景色
- (void)buttonBackGroundUpOutside:(UIButton *)sender
{
    sender.backgroundColor = [UIColor whiteColor];
}

#pragma mark - 显示方法
-(void)show {
    
    if ([LZAlertViewManager shareInstance].isShowAlert) {
        return;
    }
    
    [LZAlertViewManager shareInstance].isShowAlert = YES;
    
    [[UIApplication sharedApplication].keyWindow endEditing:YES];
    
    [[UIApplication sharedApplication].keyWindow addSubview:self];
    
    _viewAlert.layer.opacity = 0.5f;
    _viewAlert.layer.transform = CATransform3DMakeScale(1.1f, 1.1f, 1.0);
    
    // 动画
    [UIView animateWithDuration:0.2f
                          delay:0
                        options:UIViewAnimationOptionCurveEaseInOut
                     animations:^{

                         self.layer.opacity = 1.0f;
                         
                         _viewAlert.layer.opacity = 1.0f;
                         _viewAlert.layer.transform = CATransform3DMakeScale(1, 1, 1);
                     }
                     completion:nil];
}

#pragma mark - 隐藏方法
-(void)close {
    
    // 消失的动画
    
    CATransform3D currentTransform = _viewAlert.layer.transform;
    
    [UIView animateWithDuration:0.2f delay:0.0 options:UIViewAnimationOptionTransitionNone
                     animations:^{
                         
                         self.layer.opacity = 0.0f;
                         
                         _viewAlert.layer.transform = CATransform3DConcat(currentTransform, CATransform3DMakeScale(0.8f, 0.8f, 1.0));
                         _viewAlert.layer.opacity = 0.0f;
                     }
                     completion:^(BOOL finished) {
                         [LZAlertViewManager shareInstance].isShowAlert = NO;
                         [_viewAlert removeFromSuperview];
                         _viewAlert = nil;
                         [self removeFromSuperview];
                     }
     ];
}

- (void)dealloc {
    
}

@end
